<template>
  <div class="app-container">
    <a-form :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch">
      <a-form-item label="赛事名称" name="eventName">
        <a-input
          v-model:value="queryParams.eventName"
          placeholder="请输入赛事名称"
          allow-clear
          @pressEnter="handleQuery"
        />
      </a-form-item>
      <a-form-item label="赛车" name="saiche">
        <a-select
          v-model:value="queryParams.saiche"
          placeholder="请选择赛车"
          allow-clear
          style="width: 120px"
          @change="onQuerySaicheChange"
          @pressEnter="handleQuery"
        >
          <a-select-option
            v-for="item in raceOptions2"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="赛车手" name="racerName">
        <a-select
          v-model:value="queryParams.racerName"
          placeholder="请选择赛车手"
          allow-clear
          style="width: 120px"
        >
          <a-select-option
            v-for="item in raceOptions3"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button @click="resetQuery" style="margin-left: 8px">
          <template #icon><ReloadOutlined /></template>
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <a-row :gutter="10" class="mb8">
      <a-col :span="1.5">
        <a-button
          type="primary"
          @click="handleAdd"
          v-privilege="['rankSys:rankInfo:add']"
        >
          <template #icon><PlusOutlined /></template>
          新增
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
          type="default"
          :disabled="single"
          @click="handleUpdate"
          v-privilege="['rankSys:rankInfo:edit']"
        >
          <template #icon><EditOutlined /></template>
          修改
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
          type="primary"
          danger
          :disabled="multiple"
          @click="handleDelete"
          v-privilege="['rankSys:rankInfo:remove']"
        >
          <template #icon><DeleteOutlined /></template>
          删除
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
          type="default"
          @click="handleExport"
          v-privilege="['rankSys:rankInfo:export']"
        >
          <template #icon><DownloadOutlined /></template>
          导出
        </a-button>
      </a-col>
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </a-row>

    <a-table 
      :loading="loading" 
      :data-source="rankInfoList" 
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: handleSelectionChange }"
      :pagination="false"
      row-key="id"
    >
      <a-table-column title="序号" data-index="id" align="center" />
      <a-table-column title="赛事名称" data-index="eventName" align="center" />
      <a-table-column title="赛车" data-index="saiche" align="center" />
      <a-table-column title="赛车手" data-index="racerName" align="center" />
      <a-table-column title="排名" data-index="ranking" align="center" />
      <a-table-column title="积分" data-index="points" align="center" />
      <a-table-column title="完成时间" data-index="raceTime" align="center" :width="180">
        <template #default="{ record }">
          <span>{{ parseTime(record.raceTime, '{y}-{m}-{d}') }}</span>
        </template>
      </a-table-column>
      <a-table-column title="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ record }">
          <a-space>
            <a-button type="link" @click="handleUpdate(record)" v-privilege="['rankSys:rankInfo:edit']">
              <template #icon><EditOutlined /></template>
              修改
            </a-button>
            <a-button type="link" danger @click="handleDelete(record)" v-privilege="['rankSys:rankInfo:remove']">
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
          </a-space>
        </template>
      </a-table-column>
    </a-table>
    
    <div class="table-pagination" style="margin-top: 16px; text-align: right" v-show="total > 0">
      <a-pagination
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        show-size-changer
        :show-total="(total) => `共 ${total} 条`"
      />
    </div>

    <!-- 添加或修改赛事排名对话框 -->
    <a-modal :title="title" v-model:open="open" width="500px" :confirm-loading="submitLoading">
      <a-form ref="rankInfoRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="赛事名称" name="eventName">
          <a-input v-model:value="form.eventName" placeholder="请输入赛事名称" />
        </a-form-item>
        <a-form-item label="赛车" name="saiche">
          <a-select v-model:value="form.saiche" placeholder="请选择赛车车牌" allow-clear @change="onFormSaicheChange">
            <a-select-option 
              v-for="item in raceOptions2" 
              :key="item.value" 
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="赛车手" name="racerName">
          <a-select v-model:value="form.racerName" placeholder="请选择赛车手" allow-clear>
            <a-select-option 
              v-for="item in raceOptions3" 
              :key="item.value" 
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排名" name="ranking">
          <a-input v-model:value="form.ranking" placeholder="请输入排名" />
        </a-form-item>
        <a-form-item label="积分" name="points">
          <a-input v-model:value="form.points" placeholder="请输入积分" />
        </a-form-item>
        <a-form-item label="完成时间" name="raceTime">
          <a-date-picker 
            v-model:value="form.raceTime"
            value-format="YYYY-MM-DD"
            placeholder="请选择完成时间"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="cancel">取 消</a-button>
        <a-button type="primary" @click="submitForm" :loading="submitLoading">确 定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup name="RankInfo">
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue';
import { 
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue';
import { listRankInfo, getRankInfo, delRankInfo, addRankInfo, updateRankInfo ,listAllSaiduan, listAllSaiche, listAllSaicheshou } from "/@/api/offroad/rankSys/rankInfo";
const { proxy } = getCurrentInstance();

const rankInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const submitLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectedRowKeys = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    eventName: null,
    saiche: null,
    racerName: null,
    ranking: null,
    points: null,
    raceTime: null
  },
  rules: {
    eventName: [
      { required: true, message: "赛事名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
// 下拉列表数据
const raceOptions = ref([]);
const raceOptions2 = ref([]);
const raceOptions3 = ref([]);
/** 查询赛事排名列表 */
function getList() {
  loading.value = true;
  listRankInfo(queryParams.value).then(response => {
    rankInfoList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    eventName: null,
    saiche: null,
    racerName: null,
    ranking: null,
    points: null,
    raceTime: null
  };
  proxy.resetForm("rankInfoRef");
}
// 监听查询区赛车变化
function onQuerySaicheChange(val) {
  queryParams.value.racerName = null;
  raceOptions3.value = [];
  if (val) listDrivers(val);
}

// 监听弹窗区赛车变化
function onFormSaicheChange(val) {
  form.value.racerName = null;
  raceOptions3.value = [];
  if (val) listDrivers(val);
}

// 拉取赛段、赛车、赛车手
function listStages() { listAllSaiduan().then(r=> raceOptions.value = r.data.map(i=>({ value:i, label:i }))); }
function listCars()   { listAllSaiche().then(r=> raceOptions2.value = r.data.map(i=>({ value:i, label:i }))); }
function listDrivers(saiche) { listAllSaicheshou(saiche).then(r=> raceOptions3.value = r.data.map(i=>({ value:i, label:i }))); }
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selectedKeys, selectedRows) {
  selectedRowKeys.value = selectedKeys;
  ids.value = selectedRows.map(item => item.id);
  single.value = selectedRows.length != 1;
  multiple.value = !selectedRows.length;
}

// 分页页码变化
function handlePageChange(page, pageSize) {
  queryParams.value.pageNum = page;
  queryParams.value.pageSize = pageSize;
  getList();
}

// 分页大小变化
function handlePageSizeChange(current, size) {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = size;
  getList();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加赛事排名";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0];
  getRankInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改赛事排名";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["rankInfoRef"].validate().then(() => {
    submitLoading.value = true;
    if (form.value.id != null) {
      updateRankInfo(form.value).then(response => {
        proxy.$message.success("修改成功");
        open.value = false;
        getList();
      }).finally(() => {
        submitLoading.value = false;
      });
    } else {
      addRankInfo(form.value).then(response => {
        proxy.$message.success("新增成功");
        open.value = false;
        getList();
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm({
    title: '确认删除',
    content: '是否确认删除赛事排名编号为"' + _ids + '"的数据项？',
    onOk() {
      return delRankInfo(_ids).then(() => {
        getList();
        proxy.$message.success("删除成功");
      });
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('rankSys/rankInfo/export', {
    ...queryParams.value
  }, `rankInfo_${new Date().getTime()}.xlsx`)
}

getList();
onMounted(() => {
  listStages(); listCars();
  // 初次不拉drivers
  getList();
});
</script>

<style scoped>
.app-container { padding: 16px; }
.mb8 { margin-bottom: 8px; }
.small-padding { padding: 4px; }
.fixed-width { width: 120px; }
</style>